String.prototype.format = function () {
	if (arguments.length == 0) {
		return this;
	}
	for (var StringFormat_s = this, StringFormat_i = 0; StringFormat_i < arguments.length; StringFormat_i++) {
		StringFormat_s = StringFormat_s.replace(new RegExp("\\{" + StringFormat_i + "\\}", "g"), arguments[StringFormat_i]);
	}
	return StringFormat_s;
};

var app = angular.module('app', [
                                 "ngRoute",
                                 "ui.router",
                                 "ngTouch",
                                 "mobiletouch",
                                 "ui.bootstrap",
                                 "ngCordova",
                                 "ngAnimate",
                                 "ngSanitize", 'angular-loading-bar', 'ngChat'
                                 ]).config(function (cfpLoadingBarProvider) {
                                	 cfpLoadingBarProvider.includeBar = false;
                                	 cfpLoadingBarProvider.includeSpinner=false;
                                 });
app.run(function ($rootScope, $http, $location, $cordovaNetwork, $cordovaCamera, $cordovaFileTransfer
		, $cordovaProgress, $cordovaStatusbar, $cordovaChat, $cordovaFileOpener2, $timeout, $q, $state, $cordovaKeyboard, $cacheFactory,$window) {

	$rootScope.newhy = false;
	$rootScope.site = SITE_URL;
	$rootScope.localurl = LOCAL_URL;
	$rootScope.isnetwork = true;
	$rootScope.isexitapp = false;
	$rootScope.showf = true;
	$rootScope.goods_id = 0;
	$rootScope.rec_id = 0;
	$rootScope.n = 0;
	$rootScope.xstopscroll = true;

	$rootScope.fromState = '';
	$rootScope.fromParams = '';

	$rootScope.pushid = "";
	$rootScope.mask = false;
	$rootScope.fu = "";
	$rootScope.inback = false;
	$rootScope.addrregion = "";
	$rootScope.addr = "";
	$rootScope.routefrom = "";
	//消息数
	$rootScope.badge = 0;

	$rootScope.isf = true;

	$rootScope.position = "我的位置";
	$rootScope.istutor = false;
	$rootScope.vesion="";

	window.localStorage.roothistory = "";

	window.localStorage.lat = "";
	window.localStorage.lng = "";

	$rootScope.inswx=false;
	$rootScope.insqq=false;
	
	var url = SITE_URL + "index.php?app=baseloginapp&act=tutorbase&callback=JSON_CALLBACK";
	$http.jsonp(url).success(function (data) {
		if (data.done&&data.retval==true) {
			$rootScope.istutor=true;
		}
	});	

	$rootScope.focusinput = null;
	$rootScope.inputshow = function (et) {
		$rootScope.focusinput = et.target;
	}

	$window.onresize = function () {
		if ($rootScope.focusinput != null) {
			$timeout(function () {
				//$rootScope.focusinput.scrollIntoViewIfNeeded(true);
				if ($($rootScope.focusinput).offset().top > $($window).height() - 80) {
					$("#viewbd").animate({
						scrollTop: $("#viewbd").scrollTop() + $($rootScope.focusinput).offset().top - $($window).height() / 2
					}, 200);
				}
			}, 200, false);
		}
	}
	$rootScope.scan = function () {
		try {
			cordova.plugins.barcodeScanner.scan(
					function (result) {
						if (result.format != 'QR_CODE') {
							showtoast('请扫描二维码');
							return;
						}
						var retval = result.text;
						if (retval == "") {
							showtoast('请扫描准确的二维码');
							return;
						}
						retval = JSON.parse(retval);
						if (retval.type == undefined) {
							showtoast('请扫描准确的二维码');
							return;
						}

						if (retval.type == "go") {
							$rootScope.go(retval.value, retval.params);
						}

						if (retval.type == "addfriend") {
							var url = SITE_URL + "index.php?app=usersnsapp&act=addfriend&callback=JSON_CALLBACK&fuid=" + retval.value;
							$http.jsonp(url).success(function (data) {
								if (data.done) {
									showtoast(data.msg);

									$rootScope.orthermsg(data.retval.push);
								}
							});
						}
					},
					function (error) {
						showtoast('扫码失败');
						return;
					}
			);
		} catch (e) {
			showcatch(e);
		}
	};

	$rootScope.orthermsg = function (pushdata) {
		try {
			for (var i = 0; i < pushdata.length; i++) {
				var push = pushdata[i];
				var to = push.to;
				var type = push.type;
				var msg = push.msg;
				if (typeof msg == "object") {
					msg = JSON.stringify(msg);
				}

				if ($cordovaChat.ChatConnected()) {

					$cordovaChat.ChatSendMessage(to, msg, '', '', 0, '', '', type, 0).then(function (success) {

					}, function (error) {
						showtoast(error);
					});
				}
				else{
					//showtoast("发送失败");
				}
			}

		} catch (e) {
			showcatch(e);
		}
	}

	$rootScope.go = function (url, param,reload) {
		try {
			$rootScope.routefrom = "go";
			if (url != "login" && url != "loginmain" &&url != "loginmain") {
				$rootScope.fromState = url;
				$rootScope.fromParams = param;
			}

			$rootScope.xstopscroll = true;
			$rootScope.isexitapp = false;
			//if ($rootScope.httpsReject != null && $rootScope.httpsReject != undefined)
			//	$rootScope.httpsReject.resolve();
			//$rootScope.httpsReject = $q.defer();
			var l = $location;

			var regorders = new RegExp("/order[0-9]*$");
			var regorders1 = new RegExp("order[0-9]*$");

			var regtorders = new RegExp("/tutororder[0-9]*$");
			var regtorders1 = new RegExp("tutororder[0-9]*$");

			var regtnote = new RegExp("/tutornote/[0-9]*$");
			var regtconsult = new RegExp("/tutorconsult/[0-9]*$");
			var regteva = new RegExp("/tutoreva/[0-9]*$");
			var regv = new RegExp("/consultevaluation/[0-9]*$");

			var regstore = new RegExp("/store/[0-9]*$");
			var regstorecomment = new RegExp("/storecomment/[0-9]*$");

			var regbag = new RegExp("/bag/[0-9]*/[0-9]*$");
			var regchatmsg = new RegExp("/chatmsg/[0-9]*/[0-9]*$");

			var regappointtutor = new RegExp("/appointtutor/[0-9]*$");

			var replace = {};

			if (l.$$path == "/register" || l.$$path == "/comesoon" || l.$$path == "/network" 
				|| l.$$path == "/tutorname" || l.$$path == "/nickname"
					|| l.$$path == "/tutorcity" || l.$$path == "/tutortrade" || l.$$path == "/tutorop" || l.$$path == "/usersex"
						|| l.$$path == "/userage" || l.$$path == "/stage" || l.$$path == "/resetpwd" 
							|| l.$$path == "/articleid" || l.$$path == "/withdrawals"|| l.$$path == "/findpwd") {


				replace = {location: 'replace'};

			} else if (l.$$path == "/followtutorw"&&url=="followtutory") {
				replace = {location: 'replace'};
			} else if (l.$$path == "/followtutory"&&url=="followtutorw") {
				replace = {location: 'replace'};
			} else if (l.$$path == "/studenteva"&&url=="studentevawzx") {
				replace = {location: 'replace'};
			} else if (l.$$path == "/studentevawzx"&&url=="studenteva") {
				replace = {location: 'replace'};
			}else if (regv.test(l.$$path)) {
				replace = {location: 'replace'};
			}else if (regappointtutor.test(l.$$path)) {
				replace = {location: 'replace'};
			}else if (regtnote.test(l.$$path)) {
				replace = {location: 'replace'};
			}else if (regtconsult.test(l.$$path)) {
				replace = {location: 'replace'};
			}else if (regteva.test(l.$$path)) {
				replace = {location: 'replace'};
			}else if (regchatmsg.test(l.$$path)) {
				replace = {location: 'replace'};
			}else if (l.$$path == "/uedit") {
				if(url!="tutorname"&&url!="nickname"&&url!="tutortel"&&url!="tutorop"&&url!="tutoremail"&&url!="usersex"&&url!="userage"&&url!="tutorcity"&&url!="tutortrade"){
					replace = {location: 'replace'};
				}
			} else if (l.$$path == "/tutorregstep1") {
				if(url!="tutorregstep2"&&url!="nickname"&&url!="tutortel"&&url!="tutorop"&&url!="tutoremail"&&url!="usersex"&&url!="tutorname"&&url!="tutorcity"&&url!="tutortrade"){
					replace = {location: 'replace'};
				}

			} else if (l.$$path == "/tutorregstep2"&&url != "tutorregstep3") {
				replace = {location: 'replace'};

			} else if (l.$$path == "/tutorregstep3"&&url != "tutortel") {
				replace = {location: 'replace'};

			}else if (l.$$path == "/login") {
				if (url == "register" || url == "findpwd") {
				} else {
					replace = {location: 'replace'};
				}
			} else if (l.$$path == "/findquestion"&&url == "findreplay") {
				replace = {location: 'replace'};

			}else if (l.$$path == "/findreplay"&&url == "findquestion") {
				replace = {location: 'replace'};

			}else if (regorders.test(l.$$path) && regorders1.test(url)) {
				replace = {location: 'replace'};
			}else if (regtorders.test(l.$$path) && regtorders1.test(url)) {
				replace = {location: 'replace'};
			}else if (l.$$path == "/loginmain") {
				if (url != "login" && url != "register") {
					replace = {location: 'replace'};
				}
			}

			if (param == undefined || param == "" || param == null) {
				param = {};
			}

			if(replace!=null&&replace!=""){
				if(reload){
					replace = {location: 'replace',reload: true};
				}
			}else{
				if(reload){
					replace={reload: true};
				}
			}

			$state.go(url, param, replace);
			console.log('来自路由跳转：' + url + '参数：' + JSON.stringify(param));
			console.log('来自路由跳转：' + url + '参数：' + JSON.stringify(replace));
		} catch (e) {
			showcatch(e);
		}
	}

	$rootScope.back = function (a) {
		try {
			$rootScope.routefrom = "back";
			var l = $location;
			$rootScope.mask = false;
			$rootScope.xstopscroll = false;
			if ((l.$$path == "/" || l.$$path == "/findquestion" || l.$$path == "/order" || l.$$path == "/ucenter"|| l.$$path == "/loginmain")) {

				if ($rootScope.isexitapp) {
					// cordova.plugins.backgroundMode.disable();
					navigator.app.exitApp();
				}
				else {
					$rootScope.isexitapp = true;
					showtoast('再按一次退出');
					$timeout(function () {
						$rootScope.isexitapp = false;
					}, 2000);
				}
				return false;
			}

			if (window.history.length == 1) {
				$state.go('index');
			} else {
				window.history.back(-1);
			}

		} catch (e) {
			showcatch(e);
		}
	}

	$rootScope.gotoad = function (id, type, url) {
		if (type == 'goods' && id > 0) {
			$rootScope.go("goods", {'id': id});
			return false;
		}

		if (type == 'article' && id > 0) {
			$rootScope.go("article", {'id': id});
			return false;
		}

		if (type == 'store' && id > 0) {
			$rootScope.go("store", {'id': id});
			return false;
		}

		if (type == 'url' && (url != undefined && url != undefined != '')) {
			window.open(url, '_blank', 'location=yes');
			return false;
		}
		if (type == 'local' && (url != undefined && url != undefined != '')) {
			$rootScope.go(url);
			return false;
		}
	};

	$rootScope.upfilemove = function (sender, belong) {
		console.log('upfilemove=sender');
		console.log(sender);
		$.DIC.dialog({
			content: '确认要移除吗？',
			okValue: '确定',
			cancelValue: '取消',
			isMask: true,
			ok: function () {
				var url = SITE_URL + "index.php?app=appupload&act=remove&belong=" + belong + "&item_id=" + sender.$parent.item_id + "&file_id=" + sender.p.file_id + "&HTTP_USER_AGENT=" + $rootScope.HTTP_USER_AGENT + "&ECM_ID=" + $rootScope.ECM_ID + "&callback=JSON_CALLBACK";
				$http.jsonp(url).success(function (data) {
					if (data.done) {
						console.log('sender.parent.pic');
						console.log(sender.$parent.pic);
						sender.$parent.pic.splice(sender.$index, 1);
						window.localStorage.pic = JSON.stringify(sender.$parent.pic);
						console.log(sender.$parent.pic);
						// $.DIC.dialog({content:'移除成功', autoClose:true});
					} else {
						showtoast(data.msg);
					}
				});
			}
		});
	};

	$rootScope.upfile = function (belong) {
		var sender = this;
		if (sender.maxpic <= sender.pic.length) {
			showtoast('最多' + sender.maxpic + '张照片');
			return;
		}
		if (belong == undefined) {
			showtoast('参数错误');
			return;
		}
		if (sender.item_id == 0) {
			showtoast('参数错误，请重试');
			return;
		}
		var item_id = sender.item_id;
		$cordovaCamera.getPicture({
			quality: 50,
			destinationType: Camera.DestinationType.FILE_URI,
			targetWidth: 1024,
			targetHeight: 1024,
			PictureSourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM
		}).then(function (imageURI) {
			console.log(sender);
			console.log(imageURI);
			sender.src = imageURI;

			url = $rootScope.site + "index.php?app=usermyapp&act=upfile&callback=JSON_CALLBACK";
			console.log(url);
			$http.jsonp(url).success(function (data) {
				console.log(data);
				if (data.done) {
					$rootScope.ECM_ID = data.retval.userid;
					$rootScope.HTTP_USER_AGENT = data.retval.HTTP_USER_AGENT;

					var uri = $rootScope.site + 'index.php?app=appupload&ajax=ajax&XDEBUG_SESSION_START=ECLIPSE_DBGP';
					console.log(uri);
					var options = new FileUploadOptions();
					options.fileKey = "file";
					options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
					options.mimeType = "text/plain";

					var params = {};
					params.ECM_ID = $rootScope.ECM_ID;
					params.HTTP_USER_AGENT = $rootScope.HTTP_USER_AGENT;
					params.belong = belong;
					params.item_id = item_id;
					options.params = params;


					ProgressIndicator.showProgressBar('正在上传...');
					$cordovaFileTransfer.upload(uri, imageURI, options).then(function (r) {
						console.log("Code = " + r.responseCode);
						console.log("Response = " + r.response);
						console.log("Sent = " + r.bytesSent);
						ProgressIndicator.hide();
						data = JSON.parse(r.response);
						if (data.done) {
							sender.pic.push(data.retval);
							window.localStorage.pic = JSON.stringify(sender.pic);
							// alert(JSON.stringify(sender.pic));
							console.log("sender.src = " + sender.src);
						}
						else {
							$.DIC.dialog({content: data.msg, autoClose: true});
						}
					}, function (error) {
						alert("An error has occurred: Code = " + error.code);
						console.log("upload error source " + error.source);
						console.log("upload error target " + error.target);
						ProgressIndicator.hide();
						showtoast('图片选择失败' + error);
					}, function (progressEvent) {
						if (progressEvent.lengthComputable) {
							// loadingStatus.setPercentage(progressEvent.loaded
							// / progressEvent.total);
							// $cordovaProgress.showBarWithLabel(true, 100000,
							// '正在上传图片');

						} else {
							// $cordovaProgress.showBarWithLabel(true, 100000,
							// '正在上传图片');
							// loadingStatus.increment();
						}
						ProgressIndicator.setProgress(progressEvent.loaded / progressEvent.total);
					});
				}
			});

		});
	};

	$rootScope.autologin = function (s) {
		var u = window.localStorage.u;
		var p = window.localStorage.p;
		if (u != undefined && u != "" && p != undefined && p != "") {

			url = SITE_URL + "index.php?app=userapp&act=checkuser&callback=JSON_CALLBACK&u=" + u + "&p=" + p;
			$http.jsonp(url).success(function (data) {
				if (data.done) {
					var d = data.retval;
					window.localStorage.user = JSON.stringify(d);

					var requestData={};
					requestData.username = d.CHATUSER;
					requestData.password = '123456';
					requestData.nickname = d.n;

					$.ajax({
						url: 'https://a1.easemob.com/darven02/dscj/users',
						type: 'POST',
						data: JSON.stringify(requestData),
						headers: {
							'Content-Type': 'application/json'
						},
						success: function (respData) {
							console.log(respData);

						},
						error: function (respData) {
							console.log(respData);
						},
					});

					try{
						//视频连线登录
						if(window.easemobchat!=undefined)
							easemobchat.login(
									{username:d.CHATUSER,password:'123456'},
									function(s){//showtoast(window.localStorage.u+" 2");
									},

									function(e){//showtoast(window.localStorage.u+" 3");

									}
							);
					}
					catch(e){showcatch(e);}

					//$rootScope.istutor=true;
					if (!$cordovaChat.ChatConnected() && window.localStorage.user != undefined && window.localStorage.user != null && window.localStorage.user != "") {
						var d = JSON.parse(window.localStorage.user);
						$cordovaChat.init(d.BOSH_SERVICE, d.CHATURI, d.CHATUSER, d.CHATUSERP);
						$cordovaChat.ChatConnect();
					}

					if (s != 1) {
						if ($rootScope.fromState != "") {
							$rootScope.go($rootScope.fromState, $rootScope.fromParams,true);
						} else {
							$rootScope.go("index","",true);
						}
					}
				} else {
					window.localStorage.u = "";
					window.localStorage.p = "";
					window.localStorage.user = "";

					if ($cordovaChat.ChatConnected()) {
						$cordovaChat.ChatDisConnect();
					}
					if (s != 1) {
						$rootScope.go("loginmain");
					}
				}
			});
		} else {
			if (s != 1) {
				$rootScope.go("loginmain");
			}
		}
	}

	$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {

		$rootScope.loading = true;
		$rootScope.isexitapp = false;
		$rootScope.fu="";
		$.DIC.dialog({close: true});

		// 记录当前path，用于网络连接断开时处理

		//console.log('$rootScope.istutor',$rootScope.istutor);
		/*if (toState.name == 'order') {
			if ($rootScope.istutor) {
				toState.templateUrl = gettemplate('user.tutor.order.html');
				toState.controller='UserTutorOrder';
				toState.resolve.UserTutorOrderData=UserTutorOrder.UserTutorOrderData;
			}else{
				toState.templateUrl = gettemplate('user.order.html');
				toState.controller='UserOrder';
				toState.resolve.UserOrderData=UserOrder.UserOrderData;
			}
		}
		if (toState.name == 'index'){
			if ($rootScope.istutor){
				toState.templateUrl = gettemplate('user.tutor.center.html');
				toState.controller='UserTutorCenter';
				toState.resolve.UserTutorCenterData=UserTutorCenter.UserTutorCenterData;
			}else{
				toState.templateUrl = gettemplate('base.index.html');
				toState.controller='BaseIndex';
				toState.resolve.BaseIndexData=BaseIndex.BaseIndexData;
				toState.resolve.BaseIndexDefault= BaseIndex.BaseIndexDefault;
			}
		}
		if (toState.name == 'ucenter') {
			if ($rootScope.istutor) {
				toState.templateUrl = gettemplate('base.tutor.ucenter.html');
			}else{
				toState.templateUrl = gettemplate('base.ucenter.html');
			}
		}*/
		try {
			checknetwork($location, $rootScope, $cordovaNetwork);
			$cordovaKeyboard.close();
		}
		catch (e) {

		}
	});

	$rootScope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) {
		$rootScope.loading = false;
		$rootScope.isexitapp = false;
		$rootScope.fu = "";
		if ($rootScope.media != undefined && $rootScope.media != null) {
			$rootScope.media.release();
		}
		if (!$cordovaChat.ChatConnected() && window.localStorage.user != undefined && window.localStorage.user != null && window.localStorage.user != "") {
			var d = JSON.parse(window.localStorage.user);
			$cordovaChat.init(d.BOSH_SERVICE, d.CHATURI, d.CHATUSER, d.CHATUSERP);
			$timeout(function () {
				$cordovaChat.ChatConnect();
			});
		}
	});

	document.addEventListener("deviceready", function () {

		try{
			Wechat.isInstalled({scope: 'snsapi_userinfo'}, 
					function onSuccess(suc) {
				$rootScope.inswx=true;
			},
			function onError(err) {
				$rootScope.inswx=false;
			}
			);

			YCQQ.checkClientInstalled(
					function onSuccess(suc) {
						$rootScope.insqq=true;
					},
					function onError(err) {
						$rootScope.insqq=false;
					}
			);
		}catch (e) {
		}
		cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);

		document.addEventListener("pause", function () {
			$rootScope.inback = true;
		}, false);

		document.addEventListener("resume", function () {
			$rootScope.badge = 0;
			$rootScope.inback = false;
			navigator.splashscreen.hide();
		}, false);

		/*
		 * try{ cordova.plugins.backgroundMode.configure({ silent: true, title:
		 * '嗨享生活', ticker: '', text: '' });
		 * cordova.plugins.backgroundMode.enable();
		 * cordova.plugins.backgroundMode.onactivate = function() {
		 * cordova.plugins.backgroundMode.configure({ silent: true, title:
		 * '嗨享生活', ticker: '', text: '' }); };
		 * cordova.plugins.backgroundMode.ondeactivate = function() {
		 * cordova.plugins.backgroundMode.configure({ silent: true, title:
		 * '嗨享生活', ticker: '', text: '' }); };
		 * cordova.plugins.backgroundMode.onfailure = function() {
		 * cordova.plugins.backgroundMode.configure({ silent: true, title:
		 * '嗨享生活', ticker: '', text: '' }); }; }catch(e){}
		 */

		document.addEventListener("backbutton", function () {
			$rootScope.back(1);
		}, false);

		// listen for Online event
		$rootScope.$on('$cordovaNetwork:online', function (event, networkState) {
			var onlineState = networkState;
			$rootScope.go($rootScope.curpath);
		});

		// listen for Offline event
		$rootScope.$on('$cordovaNetwork:offline', function (event, networkState) {
			var offlineState = networkState;
			if ($rootScope.go().substr(0, 8) == "/network")
				return;
			$rootScope.go("network");
		});

		$rootScope.$on('$cordovaChat:ChatMessageReciveEvent', function (event, msg) {
			try {
				console.log('$cordovaChat:ChatMessageReciveEvent')
				console.log('$cordovaChat:ChatMessageReciveEvent',msg)
				if (($rootScope.fu == undefined || $rootScope.fu == "" || (msg.fromuser != $rootScope.fu.user_id && msg.fromuser != JSON.parse(window.localStorage.user).CHATUSER) && msg)) {
					$rootScope.newhy = true;
				}
				if ($rootScope.inback && cordova.plugins.notification) {

					cordova.plugins.notification.local.schedule({
						id: '1',
						// title: 'Scheduled with delay1',
						text: '你有新消息',
						data: msg,
						badge: ++$rootScope.badge
					});
				}
				else if (navigator.notification && msg.fromuser != $rootScope.fu.user_id && msg.fromuser != JSON.parse(window.localStorage.user).CHATUSER) {
					navigator.notification.beep();
					if (navigator.vibrate) {
						navigator.vibrate(200);
					}
				}
			} catch (e) {
				showcatch(e);
			}
		});


		$rootScope.$on('$cordovaChat:ChatMessageReciveNewFEvent', function (event, msg) {
			try {
				console.log('$cordovaChat:ChatMessageReciveNewFEvent')
				if (window.localStorage.user != undefined && window.localStorage.user != null && window.localStorage.user != '' && msg.touser == JSON.parse(window.localStorage.user).CHATUSER) {

					if (cordova.plugins.notification) {
						cordova.plugins.notification.local.schedule({
							id: '2',
							//title: 'Scheduled with delay1',
							text: '你有新的好友申请',
							data: {type: 'msg'},
							badge: ++$rootScope.badge
						});
					}
				}
			} catch (e) {
				showcatch(e);
			}
		});

		$rootScope.$on('$cordovaChat:ChatMessageReciveAddFEvent', function (event, msg) {
			try {
				console.log('$cordovaChat:ChatMessageReciveAddFEvent')
				if (window.localStorage.user != undefined && window.localStorage.user != null && window.localStorage.user != '' && msg.touser == JSON.parse(window.localStorage.user).CHATUSER) {

					if (cordova.plugins.notification) {
						cordova.plugins.notification.local.schedule({
							id: '3',
							//title: 'Scheduled with delay1',
							text: '好友申请通过',
							data: {type: 'msg'},
							badge: ++$rootScope.badge
						});
					}
				}
			} catch (e) {
				showcatch(e);
			}
		});

		$rootScope.$on('$cordovaChat:ChatMessageReciveOrtherEvent', function (event, msg) {
			try {
				console.log('$cordovaChat:ChatMessageReciveOrtherEvent')
				if (window.localStorage.user != undefined && window.localStorage.user != null && window.localStorage.user != '' && msg.touser == JSON.parse(window.localStorage.user).CHATUSER) {
					msg.msg = JSON.parse(msg.msg);

					if (cordova.plugins.notification) {
						cordova.plugins.notification.local.schedule({
							id: msg.msgtype,
							//title: 'Scheduled with delay1',
							text: msg.msg.text,
							data: msg.msg,
							badge: ++$rootScope.badge
						});
					}
				}
			} catch (e) {
				showcatch(e);
			}
		});

		//screen.lockOrientation('portrait');
		$rootScope.autologin(1);
		setTimeout(function() {
			navigator.splashscreen.hide();
		}, 100);
		try {
			// 更新
			if (device.platform == "Android") {
				window.plugins.updateApp.checkAndUpdate(SITE_URL + "androidVersion.json");
			}
			else {
				window.plugins.updateApp.checkAndUpdate(SITE_URL + "iosVersion.json");
			}
			window.plugins.updateApp.getAppVersion(function(v){
				$rootScope.vesion=v;
			},
			function(){

			});
		}
		catch (e) {
			showcatch(e);
		}

		try {
			cordova.plugins.notification.local.on('click', function (notification) {
				$rootScope.badge = 0;
				if (notification.id == 1) {
					notification.data = JSON.parse(notification.data);
					console.log(notification.data);
					$rootScope.go('chatmsg',{"id":notification.data.fromuser,"cid":notification.data.cid},true);
				}
				if (notification.id > 1000) {
					//1002 取消
					//1003 支付
					//1004 导师接受
					//1005 修改时间
					//1006 用户完成
					//1010 评价

					//2001 留言
					notification.data = JSON.parse(notification.data);
					if(notification.id==1002||notification.id==1003||notification.id==1006||notification.id==1010){
						$rootScope.go('tutororder1',{'id':notification.data.data},true);
					}else{
						$rootScope.go('order1',{'id':notification.data.data},true);
					}
				}
				if (notification.id == 200) {
					notification.data = JSON.parse(notification.data);
					console.log(notification);
					$rootScope.go('mycardid', {'id': notification.data.data.id});
				}
				if (notification.id == 300) {
					$rootScope.go('coupon');
				}
			});
		} catch (e) {
			showcatch(e);
		}

		if (LOCAL_URL != '/')
			window.open = cordova.InAppBrowser.open;
	}, false);

});

app.directive('myText', ['$rootScope', function ($rootScope) {
	return {
		link: function (scope, element, attrs) {
			$rootScope.$on('add', function (e, val) {
				var domElement = element[0];

				if (document.selection) {
					// domElement.focus();
					var sel = document.selection.createRange();
					sel.text = val;
					// domElement.focus();
				} else if (domElement.selectionStart || domElement.selectionStart === 0) {
					var startPos = domElement.selectionStart;
					var endPos = domElement.selectionEnd;
					var scrollTop = domElement.scrollTop;
					domElement.value = domElement.value.substring(0, startPos) + val + domElement.value.substring(endPos, domElement.value.length);
					// domElement.focus();
					domElement.selectionStart = startPos + val.length;
					domElement.selectionEnd = startPos + val.length;
					domElement.scrollTop = scrollTop;
				} else {
					domElement.value += val;
					// domElement.focus();
				}
				scope.msg = domElement.value;
				scope.$apply();

			});
			$rootScope.$on('remove', function (e) {
				var domElement = element[0];

				if (document.selection) {
					// domElement.focus();
					var sel = document.selection.createRange();
					sel.text = '';
					// domElement.focus();
				} else if (domElement.selectionStart || domElement.selectionStart === 0) {
					var startPos = domElement.selectionStart;
					var endPos = domElement.selectionEnd;
					var scrollTop = domElement.scrollTop;
					var q = domElement.value.substring(0, startPos);
					var h = domElement.value.substring(endPos, domElement.value.length);
					var val = '1';
					if (q.substring(q.length - 1, q.length) == "]") {
						var p = /\[.*?\]/g;
						var m = q.match(p);
						if (m != undefined && m.length > 0) {
							var l = m[m.length - 1];
							var b = false;
							for (var i = 0; i < $rootScope.alle.length; i++) {
								if ($rootScope.alle[i].d_key == l) {
									b = true;
									break;
								}
							}
							if (b) {
								val = l;
								q = q.substring(0, q.lastIndexOf(l));
							} else {
								q = q.substring(0, q.length - 1);
							}
						} else {
							q = q.substring(0, q.length - 1);
						}
					} else {
						q = q.substring(0, q.length - 1);
					}

					domElement.value = q + h;
					// domElement.focus();
					domElement.selectionStart = startPos - val.length;
					domElement.selectionEnd = startPos - val.length;
					domElement.scrollTop = scrollTop;
				} else {
					var q = domElement.value;
					if (q.substring(q.length - 1, q.length) == "]") {
						var p = /\[.*?\]/g;
						var m = q.match(p);
						if (m != undefined && m.length > 0) {
							var l = m[m.length - 1];
							var b = false;
							for (var i = 0; i < $rootScope.alle.length; i++) {
								if ($rootScope.alle[i].d_key == l) {
									b = true;
									break;
								}
							}
							if (b) {
								q = q.substring(0, q.lastIndexOf(l));
							} else {
								q = q.substring(0, q.length - 1);
							}
						} else {
							q = q.substring(0, q.length - 1);
						}
					} else {
						q = q.substring(0, q.length - 1);
					}

					domElement.value = "";
					// domElement.focus();
				}
				scope.msg = domElement.value;
				scope.$apply();
			});
		}
	}
}]);

app.directive('whenScrolled', function ($document, $window) {
	return function (scope, elm, attr) {
		var raw = (elm.parent().parent())[0];
		elm.bind('scroll', function () {
			if ((elm[0].offsetHeight + elm[0].scrollTop) >= elm[0].scrollHeight) {
				scope.$apply(attr.whenScrolled);
			}
		});
	};
});

app.directive('backButton', function () {
	return {
		restrict: 'A',

		link: function (scope, element, attrs) {
			element.bind('click', goBack);

			function goBack() {
				history.back();
				scope.$apply();
			}
		}
	};
});

app.directive('broadcast', function () {
	return {
		restrict: 'EA',
		link: function (scope, element, attr) {
			var slider = element.find('.slider-wrap').children(),
			bullet = element.find('ul').children(),
			length = slider.length,
			current = 0,
			temp = '',
			time = '',
			loopSpeed = 4000,
			fadeSpeed = 2000,
			loop = function () {
				slider.eq(current).fadeOut(fadeSpeed);
				bullet.eq(current).removeClass('libg');
				if (current == (length - 1)) {
					current = -1;
				}
				current += 1;
				slider.eq(current).fadeIn(fadeSpeed);
				bullet.eq(current).addClass('libg');
			};
			slider.eq(0).show();
			bullet.eq(0).addClass('libg');
			time = setInterval(loop, loopSpeed);
			bullet.on('click', function () {
				var index = $(this).index();
				slider.eq(index).fadeIn().siblings().fadeOut();
				bullet.eq(index).addClass('libg').siblings().removeClass('libg');
				clearInterval(time);
				current = index;
				time = setInterval(loop, loopSpeed);
			});
		}
	};
});

app.directive('errSrc', function () {
	return {
		link: function (scope, element, attrs) {
			element.bind('error', function () {
				if (attrs.src != attrs.errSrc) {
					attrs.$set('src', attrs.errSrc);
				}
			});
		}
	}
});

app.directive('focusMe', function ($timeout, $parse) {
	return {
		link: function (scope, element, attrs) {

			element.bind('focus', function () {
				$(element[0]).parent().parent().parent().addClass("getfocus");
			});
			element.bind('blur', function () {
				$(element[0]).parent().parent().parent().removeClass("getfocus");
			});
		}
	};
});
/*
 * <button event-focus="click" event-focus-id="email">Declarative Focus</button>
 * <button ng-click="doSomething()">Imperative Focus</button>
 * .controller('Ctrl', function($scope, focus) { $scope.doSomething = function() { //
 * do something awesome focus('email'); }; });
 */

app.factory('focus', function ($timeout, $window) {
	return function (id) {
		// timeout makes sure that it is invoked after any other event has been
		// triggered.
		// e.g. click events that need to run before the focus or
		// inputs elements that are in a disabled state but are enabled when
		// those events
		// are triggered.
		$timeout(function () {
			var element = $window.document.getElementById(id);
			if (element)
				element.focus();
		});
	};
});

app.factory('anchorScroll', function ($window) {
	function toView(element, top, height) {
		var winHeight = $(window).height();

		element = $(element);
		height = height > 0 ? height : winHeight / 10;
		$('html, body').animate({
			scrollTop: top ? (element.offset().top - height) : (element.offset().top + element.outerHeight() + height - winHeight-50)
		}, {
			duration: 200,
			easing: 'linear',
			complete: function () {
				//if (!inView(element)) {
				//element[0].scrollIntoView(!!top);
				//$(element[0]).scrollTop(100);

				$("#viewbd").animate({
					scrollTop: $("#viewbd").scrollTop() + $(element[0]).offset().top - 53
				}, 500);
				//}
			}
		});
	}

	function inView(element) {
		element = $(element);

		var win = $(window),
		winHeight = win.height(),
		eleTop = element.offset().top,
		eleHeight = element.outerHeight(),
		viewTop = win.scrollTop(),
		viewBottom = viewTop + winHeight;

		function isInView(middle) {
			return middle > viewTop && middle < viewBottom;
		}

		if (isInView(eleTop + (eleHeight > winHeight ? winHeight : eleHeight) / 2)) {
			return true;
		} else if (eleHeight > winHeight) {
			return isInView(eleTop + eleHeight - winHeight / 2);
		} else {
			return false;
		}
	}

	return {
		toView: toView,
		inView: inView
	};
})

app.directive('eventFocus', function (focus) {
	return function (scope, elem, attr) {
		elem.on(attr.eventFocus, function () {
			focus(attr.eventFocusId);
		});

		// Removes bound events in the element itself
		// when the scope is destroyed
		scope.$on('$destroy', function () {
			elem.off(attr.eventFocus);
		});
	};
});

app.factory('User', function ($http) {
	var service = {
			user: {},
			set: function (data) {
				service.user = data;
			}

	};
	return service;
});

function photoview(pos, imageurl) {
	ImagePlugin.preview(pos, imageurl);
}

function audioplay(url) {
	// Play the audio file at url
	var my_media = new Media(url,
			// success callback
			function () {
		console.log("playAudio():Audio Success");
	},
	// error callback
	function (err) {
		console.log(err);
		console.log("playAudio():Audio Error: " + err);
	}
	);
	return my_media;
}

function videoplay(url) {
	if (device.platform == "Android") {
		VideoPlayer.play(url);
	}
	else {
		window.playNativeVideo(url, function onVideoStart(strFileURL) {
		}, function onVideoFail(err) {
			showtoast('播放失败' + err)
		});
	}
}

function checknetwork($location, $rootScope, $cordovaNetwork) {
	if (LOCAL_URL == '/') {
		return;
	}
	// alert($location.path().substr(0,8));
	if ($location.path().substr(0, 8) != "/network")
		$rootScope.curpath = $location.path();
	// if(($cordovaNetwork.isOffline()||!$rootScope.isnetwork)&&$location.path().substr(0,8)!="/network"){
	if (($cordovaNetwork.isOffline()) && $location.path().substr(0, 8) != "/network") {
		$location.path("/network").replace();
		// alert('path net');
	}
}
//提示信息
function showtoast($msg) {
	if ($msg == "") return;
	if (LOCAL_URL == '/') {
		console.log($msg);
		$.DIC.dialog({content: $msg, autoClose: true});
	}
	else {
		window.plugins.toast.showShortCenter($msg);
		console.log($msg);
	}
}

function showdialog(msg,btn){
	if(btn==undefined||btn==null||btn==""){
		btn="确定";
	}
	$.DIC.dialog({
		id:"loginw",
		content:"<div class=\"mask_login\"><div class=\"login_error\"><p>"+msg+"</p><a href=\"javascript:void(0);\" class=\"bigbtn forclose\" id=\"forclose\">"+btn+"</a></div></div>",
		isMask:true,
		isHtml:true,
		//autoClose:2000,
		top:125
	});
}
//catch输出
function showcatch(e) {
	console.log("自定义错误 = ", "name: " + e.name + " | message: " + e.message + " | lineNumber: " + e.lineNumber + " | fileName: " + e.fileName + " | stack: " + e.stack);
	//showtoast("自定义错误 = ", "name: " + e.name + " | message: " + e.message + " | lineNumber: " + e.lineNumber + " | fileName: " + e.fileName);
}
responset = null;
app.factory('requestRejector', function ($q, $location, $rootScope, $cordovaNetwork) {
	// https请求timeout拒绝
	//if ($rootScope.httpsReject == null)
	//	$rootScope.httpsReject = $q.defer();
	var requestRejector = {
			request: function (config) {
				//config.timeout = $rootScope.httpsReject.promise;
				// config.requestTimestamp = new Date().getTime();
				if (config.url.indexOf('.php?') > -1)
					config.url = config.url + "&XDEBUG_SESSION_START=ECLIPSE_DBGP";
				// console.log('The request begin ' + config.url);
				console.log('request', config);
				return config;
			},
			response: function (response) {
				$rootScope.isnetwork = true;
				response.config.responseTimestamp = new Date().getTime();
				// console.log('The request end ' +
				// ((response.config.responseTimestamp -
				// response.config.requestTimestamp) / 1000) + '
				// seconds.'+response.config.url);
				console.log(response.config.url, response);
				responset = response;
				if (response.data.done != undefined && !response.data.done) {
					if (response.data.msg == 'login failed') {
						$rootScope.autologin();

					} else {
						if(response.data.msg!="登录失败"){
							showtoast(response.data.msg)
						}
					}
				}
				return response;
			},
			requestError: function (rejectReason) {
				console.log('rejectReason');
				console.log(rejectReason);
				showtoast(rejectReason);
				checknetwork($location, $rootScope, $cordovaNetwork);
				return $q.reject(rejectReason);
			},
			responseError: function (response) {
				console.log('The request responseError ' + response.config.url);
				// alert('The request responseError '+response.config.url);
				console.log(response);
				if (response.config.url.substr(0, SITE_URL.length) != SITE_URL)
					return $q.reject(response);
				if(response.status!=200)
					checknetwork($location, $rootScope, $cordovaNetwork);
				if (LOCAL_URL == '/') {
					// showtoast('网络连接失败');
				}
				else {
					if ($rootScope.isnetwork) {
						$rootScope.isnetwork = false;
						// showtoast('网络连接失败');
					}
					checknetwork($location, $rootScope, $cordovaNetwork);
				}
				return $q.reject(response);
			}
	};
	return requestRejector;
});

function gettemplate(url) {
	try {
		var fileURL = LOCAL_URL + url;

		//fileURL = "http://192.168.0.151:8051/"+url;

		return fileURL;

		console.log('fileURL=' + fileURL);

	}
	catch (e) {
		console.log(e);
		return fileURL;
	}
	return fileURL;
}

app.filter('html', [
                    '$sce', function($sce) {
                    	return function(text) {
                    		return $sce.trustAsHtml(text);
                    	}
                    }
                    ]);

app.filter('cut', function () {
	return function (value, wordwise, max, tail) {
		if (!value) return '';

		max = parseInt(max, 10);
		if (!max) return value;
		if (value.length <= max) return value;

		value = value.substr(0, max);
		if (wordwise) {
			var lastspace = value.lastIndexOf(' ');
			if (lastspace != -1) {
				value = value.substr(0, lastspace);
			}
		}

		return value + (tail || ' …');
	};
});

app.filter('metre', function () {
	return function (value) {
		var retval="";
		if(value==undefined||value==null||value==""||isNaN(value)){
			value=0;
		}
		value=value*1000;
		if(value<100){
			retval="<100m";
		}else if(value<1000){
			retval=value+"m";
		}else{
			retval=parseFloat(value/1000).toFixed(2)*100/100+"km";
		}
		return retval;
	};
});

app.filter('price', function () {
	return function (value) {
		var retval="";
		if(value==undefined||value==null||value==""||isNaN(value)){
			value=0;
		}
		retval=parseFloat(value).toFixed(2)*100/100;
		retval="¥"+retval;
		return retval;
	};
});
app.filter('price1', function () {
	return function (value) {
		var retval="";
		if(value==undefined||value==null||value==""||isNaN(value)){
			value=0;
		}
		retval=parseFloat(value).toFixed(2)*100/100;

		return retval;
	};
});

app.filter('age', function () {
	return function (value) {
		var retval="";
		if(value==undefined||value==null||value==""||isNaN(value)){
			value="";
		}
		if(value>150){
			value="";
		}
		retval=value;
		return retval;
	};
});

app.filter('N', function () {
	return function (value) {
		var retval="";
		if(value==undefined||value==null||value==""||isNaN(value)){
			value=0;
		}
		if(value>1000&&value<10000){
			retval=parseFloat(value/1000).toFixed(1)*10/10+"K";
		}else if(value>10000){
			retval=parseFloat(value/10000).toFixed(1)*10/10+"W";
		}else{
			retval=value;
		}

		return retval;
	};
});

app.filter('intval', function () {
	return function (value) {
		var retval="";
		if(value==undefined||value==null||value==""||isNaN(value)){
			value=0;
		}
		retval=parseInt(value);

		return retval;
	};
});

app.filter('date', function ($http) {
	return function (value) {
		if(value!=""){

			value = value.replace("-", "/");
			var day=new Date(value);
			var m=day.getMonth()+1;
			var d=day.getDate();
			var h=day.getHours();
			var mi=day.getMinutes();
			var s=day.getSeconds();
			if(m<10){
				m="0"+m;
			}
			if(d<10){
				d="0"+d;
			}
			if(h<10){
				h="0"+h;
			}
			if(mi<10){
				mi="0"+mi;
			}
			if(s<10){
				s="0"+s;
			}
			return m+"-"+d+" "+h+":"+mi+":"+s;


		}else{
			return value;
		}
	};
});

app.animation('.hide-animation', function () {
	return {
		beforeAddClass : function(element, className, done) {
			if (className === 'ng-hide') {
				element.animate({
					opacity: 0
				},500, done);
			} else {
				done();
			}
		},
		removeClass : function(element, className, done) {
			if (className === 'ng-hide') {
				element.css('opacity',0);
				element.animate({
					opacity: 1
				}, 500, done);
			} else {
				done();
			}
		}
	};
});
app.directive('touchArea', ['$touch','$timeout', function($touch,$timeout){
	// Runs during compile
	return {
		restrict: 'A',
		link: function($scope, elem,$attrs) {
			//$scope.touch = null;
			var timeoutHandler;
			var onStage = false;
			$touch.bind(elem, {
				start: function(touch) {
					//$scope.touch = touch;
					console.log('touchstart');

					if (onStage) return false;
					onStage = true;
					// Locally scoped variable that will keep track of the long press
					$scope.longPress = true;

					if(!$scope.v_start)
					{timeoutHandler=$timeout(function(){
						if($scope.longPress&&onStage){
							$scope.itemOnLongPress();
						}
						onStage = false;
					},600);
					}
					$scope.$apply();
//					if($scope.timerstart!=null){
//					window.clearTimeout($scope.timerstart);
//					}
//					$scope.timerstart=window.setTimeout($scope.itemOnLongPress(),1000);
				},

				cancel: function(touch) {
					console.log('touchcancel');
					$scope.longPress = false;
					$scope.itemOnTouchMove();
					//$scope.touch = touch;
					//$scope.$apply();
				},

				move: function(touch) {
					//console.log('touchmove');
					//console.log(touch.distanceY);
					$scope.longPress = false;
					if($scope.v_start)
					{
						if(touch.distanceY<=-40||touch.distanceY>=40){
							$scope.v_move=1;
						}else{
							$scope.v_move=0;
						}
					}
					onStage = false;
					$scope.$apply();
				},

				end: function(touch) {
					console.log('touchend');
					//$("body").css("overflow","auto");
					$scope.longPress = false;
					if($scope.v_start)
					{
						if(touch.distanceY<=-40||touch.distanceY>=40){
							$scope.itemOnTouchMove();
						}else{
							$scope.itemOnTouchEnd();
						}
						onStage = false;
						$scope.$apply();
					}
				}
			});
		}
	};
}]);


app.directive('touchMove', ['$touch','$timeout', function($touch,$timeout){
	// Runs during compile
	return {
		restrict: 'A',
		link: function($scope, elem,$attrs) {
			//$scope.touch = null;
			var timeoutHandler;
			var onStage = false;
			$touch.bind(elem, {
				start: function(touch) {},
				cancel: function(touch) {},
				end: function(touch) {},
				move: function(touch) {
					console.log(touch);
					if(touch.distanceY>=-10||touch.distanceY<=10){
						var x=touch.x;
						var s=$(".reply_star_p").offset().left;

						var now=x-s;

						var l=parseInt(now/25);
						if(l>4){
							l=4;
						}
						$scope.sarray=new Array();
						for ( var i = 0; i <=l ; i++) {
							$scope.sarray[i]=i;
						}
					}
					$scope.$apply();
				}
			});
		}
	};
}]);

app.directive('clearLink', ['$timeout', function($timeout){
	// Runs during compile
	return {
		restrict: 'A',
		link: function($scope, elem,$attrs) {
			var prev= elem[0].previousElementSibling;
			$(prev).bind('focus',function () {
				if($(prev).val()!=""){
					$(elem[0]).show();
				}else{
					$(elem[0]).hide();
				}
			});
			
			$(prev).bind('keyup',function () {
				if($(prev).val()!=""){
					$(elem[0]).show();
				}else{
					$(elem[0]).hide();
				}
			});
			
			$(prev).bind('blur',function () {
				$timeout(function(){
					$(elem[0]).hide();
				},100);
			});

			elem.bind('click', function () {
				$(elem[0]).hide();
				$(prev).focus();

				if($attrs.clear!=undefined&&$attrs.clear!=""){
					$scope.$eval($attrs.clear);
					$scope.$apply();
				}
			});
		}
	};
}]);

function bannner_height(css_demo,proportion){
	var width = $("."+css_demo+"").width();
	var height = width * proportion;
	$("."+css_demo+"").height(height);

	if(css_demo=='main_visual'){
		$("."+css_demo+"").css('line-height',height+"px");
	}
}

function razor(t,c,d){
	try{
		switch(t)
		{
		case 'resume':
			Cobub.resume({activity:c},function success(){
				console.log('resume in '+c);
			},function error(err){
				console.log('resume err'+err);
			});
			break;
		case 'pause':
			Cobub.pause({activity:c},function success(){
				console.log('pause in '+c);
			},function error(err){
				console.log('pause err'+err);
			});
			break;
		case 'error':
			if(d.n==undefined||d.n==null){
				d.n="";
			}
			Cobub.error({activity:c,errorinfo:d.n},function success(){
				console.log('error in '+c+' '+d.n);
			},function error(err){
				console.log('error err'+err);
			});
			break;
		case 'event':
			/*
			 * 事件
			 * activity 页面名称
			 * id 事件名称
			 * 上面2个参数必须
			 * label 分类
			 * acc 点击次数
			 * */
			if(d.id==undefined||d.id==null){
				d.id="";
			}
			if(d.l==undefined||d.l==null){
				d.l="";
			}
			if(d.a==undefined||d.a==null||d.a==""){
				d.a=1;
			}
			Cobub.event({id:d.id,activity:c,label:d.l,acc:d.a},function success(){
				console.log('event in '+c+' '+id);
			},function error(err){
				console.log('event err'+err);
			});
			break;
		case 'user':
			if(d.uid==undefined||d.uid==null||d.uid==""){
				d.uid=0;
			}
			Cobub.user({userid:d.uid},function success(){
				console.log('user');
			},function error(err){
				console.log('user err'+err);
			});
			break;
		case 'posttags':
			if(d.t==undefined||d.t==null){
				d.t="";
			}
			Cobub.posttags({tagsid:d.t},function success(){
				console.log('posttags');
			},function error(err){
				console.log('posttags err'+err);
			});
			break;
		case 'postwebpage':
			if(d.p==undefined||d.p==null){
				d.p="";
			}
			Cobub.postwebpage({webpage:d.p},function success(){
				console.log('webpage');
			},function error(err){
				console.log('webpage err'+err);
			});
			break;
		default:
			break;
		}
	}catch(e){showcatch(e);}
}